﻿//var webUrl = $().SPServices.SPGetCurrentSite();  //Get the current site url
//var mainMegaMenuListName = 'MegaMenuMain'; //Set the list name to the main level menu items
//var subMegaMenuListName = 'MegaMenuSub'; //Set the list name to the sub level menu items
//var divMegaMenuId = 'mega-menu-3';

/* 
===========================================================================================================
*	Array prototype to remove duplicates from array based on ParentMenu and SubCategory
*	This was added as I was unable to get the GroupBy Function within the GetMegaMenuSubCategories function to work correctly.
===========================================================================================================
*/ 
Array.prototype.uniqueSubCategories = function () {
    var r = [];
    o:for(var i = 0, n = this.length; i < n; i++)
    {
        for(var x = 0, y = r.length; x < y; x++)
        {
                if(r[x]["SubCategory"] == this[i]["SubCategory"] && r[x]["ParentMenu"] ==  this[i]["ParentMenu"].split(';#')[1])
                {
                	this.splice(x); //Item, if duplicate, is removed via splice
                    continue o;
                }
        }
        r.push({
        	"SubCategory": this[i]["SubCategory"],
        	"ParentMenu": this[i]["ParentMenu"].split(';#')[1],
        	"ParentMenuId" : this[i]["ParentMenu"].split(';#')[0]
        });
    }
    return r;
}


/* 
===========================================================================================================
*	This method serves to create the proper HTML UnOrdered list structure for our Mega Menu
===========================================================================================================
*/ 
function getMegaMenuUL()
{
	var ulMenuContent = '';
	var ulSubMenuContent = '';
	
	//Get Main Menu Items=============================================================
	var MainItems = []; //[Title, Url, MenuOrder]
	MainItems = GetMegaMenuMain(mainMegaMenuListName);

	//Piece together the Main Menu UL architecture
	for (var i = 0; i < MainItems.length; i++) {
	  var Title = MainItems[i]["Title"];
	  var Url = MainItems[i]["Url"];
	  var MenuOrder = MainItems[i]["MenuOrder"];
	  ulMenuContent += '<li>';
	  ulMenuContent += '<a href="' + Url + '">' + Title + '</a>';
	  ulMenuContent += '<ul id="' + Title + '"></ul>';
	  ulMenuContent += '</li>';
	}
	
	//Append the Main Level Menu structure so we can access it via jquery later
	$('#' + divMegaMenuId ).append(ulMenuContent);
	
	//Get Sub Menu Items & Categories==============================================================
	var SubItemCategories = []; //[ParentMenu,SubCategory]
	SubItemCategories = GetMegaMenuSubCategories(subMegaMenuListName);
	SubItemCategories = SubItemCategories.uniqueSubCategories();
	
	//Piece together the Sub Menu UL architecture
	for (var icat = 0; icat  < SubItemCategories.length; icat ++) {
	  var SubItemCategoriesSubCategory = SubItemCategories[icat ]["SubCategory"]; //get the subcategory from array
	  var SubItemCategoriesParentMenuId = SubItemCategories[icat ]["ParentMenuId"]; //uses ParentId in caml where clause later
	  var SubItemCategoriesParentMenu = SubItemCategories[icat ]["ParentMenu"]; //get the parentmenu name from array 
	  var SubItemCategoriesUrl = '#' //You could if you want to place a URL on the subCategory header but strictly optional
	  
	  //create subcategory node
	  ulSubMenuContent += '<li>';
	  ulSubMenuContent += '<a href="' + SubItemCategoriesUrl + '">' + SubItemCategoriesSubCategory + '</a>';
	  ulSubMenuContent += '<ul>';
	  
	  //get items for each parent and subcategory
	  var SubMenuCategoryItems=[] //[Title, Url, ParentMenu, MenuOrder, SubCategory];
	  SubMenuCategoryItems = GetMegaMenuSubItems(subMegaMenuListName, SubItemCategoriesParentMenu ,SubItemCategoriesParentMenuId , SubItemCategoriesSubCategory );
	  for (var itm = 0; itm < SubMenuCategoryItems.length; itm++) {
	  	var SubItemUrl = SubMenuCategoryItems[itm]['Url']; //get the sub category item url
	  	var SubItemTitle = SubMenuCategoryItems[itm]['Title']; //get the sub category item title
	  	ulSubMenuContent += '<li>';
	  	ulSubMenuContent += '<a href="' + SubItemUrl + '">' + SubItemTitle + '</a>';
	  	ulSubMenuContent += '</li>';
	  };

	  ulSubMenuContent += '</li></ul>';
	  ulSubMenuContent += '</li>';

	  $('#' + SubItemCategoriesParentMenu).append(ulSubMenuContent); //Add the sub item content to the appropriate main menu container parent item based on ID we created in the Get Main Menu Items loop above.
	  ulSubMenuContent = ''; //clear our subitem content variable between loops
	}
}


/* 
===========================================================================================================
*	This method serves to get our Main Parent menu items from the list
===========================================================================================================
*/ 
function GetMegaMenuMain(ListName)
{
	var camlViewFields = '<ViewFields>';
	camlViewFields += '<FieldRef Name="LinkTitle" />';
	camlViewFields += '<FieldRef Name="URL" />';
	camlViewFields += '<FieldRef Name="MenuOrder" />';
	camlViewFields += '</ViewFields>';

	var camlQuery = '<Query>';
	
	camlQuery += '<Where><Eq>'
	camlQuery += '<FieldRef Name="isEnabled" /><Value Type="Integer">1</Value>';
	camlQuery += '</Eq></Where>';
	
	camlQuery += '<OrderBy>';
	camlQuery += '<FieldRef Name="MenuOrder" Ascending="TRUE" />';
	camlQuery += '</OrderBy>';
	
	camlQuery += '</Query>';
	
	var menuItemArray = []; 
	
	$().SPServices({
		webURL: webUrl ,
		listName: ListName,
		operation: 'GetListItems',
		CAMLViewFields: camlViewFields,
		CAMLQuery: camlQuery ,
		async: false,
		completefunc: function (xData, Status) 
		{
		  	$(xData.responseXML).SPFilterNode('z:row').each(function() {
		  		menuItemArray.push({
		  			Title: $(this).attr('ows_LinkTitle') ,
		  			Url: $(this).attr('ows_URL'),
		  			MenuOrder: $(this).attr('ows_MenuOrder')
		  		});
		  	});
		}
	});	
	return menuItemArray;
}

/* 
===========================================================================================================
*	This method serves to produce the Sub Menu Items for each Parent Menu / Sub Menu Category combination
===========================================================================================================
*/ 
function GetMegaMenuSubItems(ListName,ParentMenu, ParentMenuId,SubCategory)
{
	var camlViewFields = '<ViewFields>';
	camlViewFields += '<FieldRef Name="LinkTitle" />';
	camlViewFields += '<FieldRef Name="URL" />';
	camlViewFields += '<FieldRef Name="ParentMenu" />';
	camlViewFields += '<FieldRef Name="MenuOrder" />';
	camlViewFields += '<FieldRef Name="SubCategory" />';
	camlViewFields += '</ViewFields>';
	
	var camlQuery = '<Query>';
	camlQuery += '<Where>';
	camlQuery += '<And>';				
	camlQuery += '<And>';
	camlQuery += '<Eq>';
	camlQuery += '<FieldRef Name="isEnabled" /><Value Type="Integer">1</Value>';
	camlQuery += '</Eq>';
	camlQuery += '<Eq>';
	camlQuery += '<FieldRef Name="SubCategory" /><Value Type="Text">' + SubCategory + '</Value>';
	camlQuery += '</Eq>';
	camlQuery += '</And>';
	camlQuery += '<Eq>';
	camlQuery += '<FieldRef Name="ParentMenu" LookupId="TRUE" /><Value Type="Lookup">' + ParentMenuId + '</Value>';
	camlQuery += '</Eq>';
	camlQuery += '</And>';				
	camlQuery += '</Where>';
	
	camlQuery += '<OrderBy>';
	camlQuery += '<FieldRef Name="MenuOrder" Ascending="TRUE" />';
	camlQuery += '<FieldRef Name="SubCategory" Ascending="TRUE" />';
	camlQuery += '</OrderBy>';
	camlQuery += '</Query>';
	
	var menuItemArray = []; //[Title, Url, Parent, Order, CategoryName]

	$().SPServices({
		webURL: webUrl ,
		listName: ListName,
		operation: 'GetListItems',
		CAMLViewFields: camlViewFields,
		CAMLQuery: camlQuery ,
		async: false,
		completefunc: function (xData, Status) 
		{
		  	$(xData.responseXML).SPFilterNode('z:row').each(function() {
			  	menuItemArray.push({
		  			Title: $(this).attr('ows_LinkTitle') ,
		  			Url: $(this).attr('ows_URL'),
		  			ParentMenu: $(this).attr('ows_ParentMenu').split(';#')[1],
		  			MenuOrder: $(this).attr('ows_MenuOrder'),
			  		SubCategory: $(this).attr('ows_SubCategory')
			  	});
		  	});
		}
	});	
	return menuItemArray;
}


/* 
===========================================================================================================
*	This method serves to produce the array of sub menu categories. 
*	TODO: correct the CAML GroupBy problem to return unique items. 
*		(this will fix having to use the unique prototype on the array above)
===========================================================================================================
*/ 
function GetMegaMenuSubCategories(ListName)
{
	var camlViewFields = '<ViewFields>';
	camlViewFields += '<FieldRef Name="ParentMenu" />';
	camlViewFields += '<FieldRef Name="SubCategory" />';
	camlViewFields += '</ViewFields>';
	
	var camlQuery = '<Query>';
	camlQuery += '<Where>';
	camlQuery += '<Eq>';
	camlQuery += '<FieldRef Name="isEnabled" /><Value Type="Integer">1</Value>';
	camlQuery += '</Eq>';
	camlQuery += '</Where>';

	camlQuery += '<OrderBy>';
	camlQuery += '<FieldRef Name="SubCategory" Ascending="TRUE" />';
	camlQuery += '</OrderBy>';

	/*
		Need to add a functional GroupBy here to eliminate the Array Prototype above.
	*/
	
	camlQuery += '</Query>';
	
	var menuItemArray = []; //[ParentMenu, SubCategory]
	
	$().SPServices({
		webURL: webUrl ,
		listName: ListName,
		operation: 'GetListItems',
		CAMLViewFields: camlViewFields,
		CAMLQuery: camlQuery ,
		async: false,
		completefunc: function (xData, Status) 
		{
		  	$(xData.responseXML).SPFilterNode('z:row').each(function() {
			  	menuItemArray.push({
		  			ParentMenu: $(this).attr('ows_ParentMenu'),
			  		SubCategory: $(this).attr('ows_SubCategory')
			  	});
		  	});									  	
		}
	});	
	return menuItemArray;
}